<template>
  <div class="recycle-container">
    <el-container>
      <!-- 顶部导航 -->
      <el-header class="header">
        <div class="header-left">
          <h2>YY云盘</h2>
        </div>
        <div class="header-right">
          <el-dropdown @command="handleCommand">
            <span class="user-info">
              <el-icon><User /></el-icon>
              {{ userStore.userInfo?.nickname || '用户' }}
              <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <el-container>
        <!-- 侧边栏 -->
        <el-aside width="150px" class="sidebar">
          <el-menu
            :default-active="$route.path"
            router
            background-color="#f5f5f5"
            text-color="#333"
            active-text-color="#409eff"
          >
            <el-menu-item index="/files">
              <el-icon><Folder /></el-icon>
              <span>我的文件</span>
            </el-menu-item>
            <el-menu-item index="/uploads">
              <el-icon><Upload /></el-icon>
              <span>上传列表</span>
            </el-menu-item>
            <el-menu-item index="/share">
              <el-icon><Share /></el-icon>
              <span>我的分享</span>
            </el-menu-item>
            <el-menu-item index="/recycle">
              <el-icon><Delete /></el-icon>
              <span>回收站</span>
            </el-menu-item>
          </el-menu>
        </el-aside>

        <!-- 主内容区 -->
        <el-main class="main-content">
          <!-- 回收站提示 -->
          <div class="page-header">
            <div class="tips">
              <el-icon><InfoFilled /></el-icon>
              <span>回收站文件保留30天，过期将自动清理</span>
            </div>
          </div>

          <!-- 工具栏 -->
          <div class="toolbar">
        <div class="toolbar-left">
          <span class="count-info">共 {{ total }} 个文件</span>
        </div>
        <div class="toolbar-right">
          <el-button type="danger" @click="handleClearAll" :disabled="recycleList.length === 0">
            <el-icon><Delete /></el-icon>
            清空回收站
          </el-button>
          <el-button type="primary" @click="handleRestoreSelected" :disabled="selectedFiles.length === 0">
            <el-icon><RefreshRight /></el-icon>
            恢复选中
          </el-button>
          <el-input
            v-model="searchKeyword"
            placeholder="搜索回收站文件"
            style="width: 200px; margin-left: 10px"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>

          <!-- 文件列表 -->
        <div v-loading="loading" class="recycle-content">
          <el-table
            :data="recycleList"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column label="文件名" min-width="300">
              <template #default="scope">
                <div class="file-name-cell">
                  <el-icon class="file-icon" :size="20">
                    <Folder v-if="scope.row.isFolder === 1" />
                    <Document v-else />
                  </el-icon>
                  <span class="file-name">{{ scope.row.fileName }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="原始路径" min-width="200">
              <template #default="scope">
                <span class="original-path">{{ scope.row.originalPath }}</span>
              </template>
            </el-table-column>
            <el-table-column label="大小" width="120">
              <template #default="scope">
                {{ scope.row.isFolder === 1 ? '-' : formatFileSize(scope.row.fileSize) }}
              </template>
            </el-table-column>
            <el-table-column label="删除时间" width="180">
              <template #default="scope">
                {{ formatTime(scope.row.deleteTime) }}
              </template>
            </el-table-column>
            <el-table-column label="剩余天数" width="100">
              <template #default="scope">
                <el-tag
                  :type="scope.row.remainingDays <= 7 ? 'danger' : scope.row.remainingDays <= 15 ? 'warning' : 'success'"
                >
                  {{ scope.row.remainingDays }}天
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button-group>
                  <el-button size="small" @click="handleRestore(scope.row)">
                    <el-icon><RefreshRight /></el-icon>
                    恢复
                  </el-button>
                  <el-button size="small" type="danger" @click="handlePermanentDelete(scope.row)">
                    <el-icon><Delete /></el-icon>
                    彻底删除
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>

          <!-- 空状态 -->
          <el-empty v-if="!loading && recycleList.length === 0" description="回收站为空" />
        </div>

        <!-- 分页 -->
        <div class="pagination" v-if="total > 0">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        </el-main>
      </el-container>
    </el-container>

    <!-- 个人信息对话框 -->
    <UserProfileDialog v-model="showProfileDialog" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { getRecycleFileList, restoreFile, permanentDeleteFile, clearRecycleBin, type FileInfo } from '@/api/file'
import UserProfileDialog from '@/components/UserProfileDialog.vue'
import {
  User,
  ArrowDown,
  Folder,
  Document,
  Search,
  Delete,
  RefreshRight,
  InfoFilled,
  Upload,
  Share
} from '@element-plus/icons-vue'

const userStore = useUserStore()

// 回收站文件信息接口 - 继承FileInfo并扩展删除相关字段
interface RecycleFileInfo extends FileInfo {
  originalPath?: string
  deleteTime?: string
  remainingDays?: number
}


// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const recycleList = ref<RecycleFileInfo[]>([])
const selectedFiles = ref<RecycleFileInfo[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const showProfileDialog = ref(false)


// 处理用户菜单命令
const handleCommand = (command: string) => {
  switch (command) {
    case 'profile':
      showProfileDialog.value = true
      break
    case 'logout':
      userStore.logout()
      break
  }
}

// 获取回收站列表
const fetchRecycleList = async () => {
  try {
    loading.value = true

    const response = await getRecycleFileList({
      page: currentPage.value,
      size: pageSize.value,
      orderBy: 'updateTime',
      orderType: 'desc'
    })

    // 处理回收站文件数据，计算剩余天数等
    recycleList.value = response.content.map(file => ({
      ...file,
      originalPath: file.parentPath || '/',  // 使用parentPath作为原始路径
      deleteTime: file.updateTime,  // 使用updateTime作为删除时间
      remainingDays: calculateRemainingDays(file.updateTime)  // 计算剩余天数
    }))

    total.value = response.total
  } catch (error: any) {
    ElMessage.error(error.message || '获取回收站列表失败')
  } finally {
    loading.value = false
  }
}

// 计算剩余天数
const calculateRemainingDays = (deleteTime: string): number => {
  const deleteDate = new Date(deleteTime)
  const now = new Date()
  const diffTime = 30 * 24 * 60 * 60 * 1000 - (now.getTime() - deleteDate.getTime()) // 30天
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return Math.max(0, diffDays)
}

// 处理选择变化
const handleSelectionChange = (selection: RecycleFileInfo[]) => {
  selectedFiles.value = selection
}

// 单个文件恢复
const handleRestore = async (file: RecycleFileInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要恢复"${file.fileName}"吗？`,
      '确认恢复',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    await restoreFile(file.id)
    ElMessage.success('文件恢复成功')
    fetchRecycleList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '恢复失败')
    }
  }
}

// 批量恢复选中文件
const handleRestoreSelected = async () => {
  if (selectedFiles.value.length === 0) {
    ElMessage.warning('请先选择要恢复的文件')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要恢复选中的 ${selectedFiles.value.length} 个文件吗？`,
      '确认批量恢复',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    // 逐个恢复文件
    for (const file of selectedFiles.value) {
      await restoreFile(file.id)
    }

    ElMessage.success(`成功恢复 ${selectedFiles.value.length} 个文件`)
    selectedFiles.value = []
    fetchRecycleList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '批量恢复失败')
    }
  }
}


// 永久删除单个文件
const handlePermanentDelete = async (file: RecycleFileInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要彻底删除"${file.fileName}"吗？删除后无法恢复！`,
      '确认彻底删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error'
      }
    )

    await permanentDeleteFile(file.id)
    ElMessage.success('文件已彻底删除')
    fetchRecycleList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 清空回收站
const handleClearAll = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要清空回收站吗？所有文件将被彻底删除，无法恢复！`,
      '确认清空回收站',
      {
        confirmButtonText: '确定清空',
        cancelButtonText: '取消',
        type: 'error'
      }
    )

    await clearRecycleBin()
    ElMessage.success('回收站已清空')
    fetchRecycleList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '清空失败')
    }
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchRecycleList()
}

// 处理页面大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchRecycleList()
}

// 处理当前页变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchRecycleList()
}

// 格式化文件大小
const formatFileSize = (size: number): string => {
  if (size === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(size) / Math.log(k))
  return parseFloat((size / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化时间
const formatTime = (time: string): string => {
  return new Date(time).toLocaleString()
}

// 初始化
onMounted(() => {
  fetchRecycleList()
})
</script>

<style scoped>
.recycle-container {
  height: 100vh;
  width: 100vw;
  background: #f8f9fa;
}

.el-container {
  height: 100%;
  width: 100%;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  border-bottom: 1px solid #e6e6e6;
  padding: 0 20px;
}

.header-left h2 {
  margin: 0;
  color: #409eff;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: #f5f5f5;
}

.sidebar {
  background-color: #f5f5f5;
  border-right: 1px solid #e6e6e6;
}

.main-content {
  background: #f8f9fa;
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 0 20px;
  background: #fff;
  border-bottom: 1px solid #e6e6e6;
}

.page-title h3 {
  margin: 0 0 5px 0;
  color: #333;
}

.header-left h2 {
  margin: 0;
  color: #333;
}

.tips {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #666;
  font-size: 14px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #fff;
  border-bottom: 1px solid #e6e6e6;
}

.count-info {
  color: #666;
  font-size: 14px;
}

.main-content {
  padding: 0;
}

.recycle-content {
  padding: 20px;
  min-height: 400px;
}

.file-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-icon {
  color: #409eff;
}

.file-name {
  cursor: pointer;
}

.file-name:hover {
  color: #409eff;
}

.original-path {
  color: #666;
  font-size: 13px;
}

.pagination {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: #fff;
}

</style>